class_name ActorContainer
extends Node2D



@onready var spawns: Node2D = $Spawns


## 主场球队名
@export var home_team: String
## 客场球队名
@export var away_team: String




## 主场球门
var home_goal: Goal:
	get: return _golas[Goal.GoalLocation.HOME]
## 客场球门
var away_goal: Goal:
	get: return _golas[Goal.GoalLocation.AWAY]

var _golas: Dictionary[Goal.GoalLocation, Goal] = {}


## 球的引用
var ball: Ball:
	get: return _ball
# 球，由 group 查找到，此变量不应该被直接使用，也不应该被设置为空值
var _ball: Ball



func _ready():
	await get_tree().process_frame
	_golas = Sundry.find_goals(get_tree())
	_ball = Sundry.find_ball(get_tree())

	# 生成主场和客场球员
	_spawn_home_away()




func _spawn_home_away():
	prints("---- home")
	_spawn_players(home_team, home_goal)
	# 生成客场前，交换x缩放
	spawns.scale.x = -1
	prints("---- away")
	_spawn_players(away_team, away_goal)


func _spawn_players(country: String, own_goal: Goal):
	var player_resources := DataLoader.get_squad(country)
	if not player_resources or player_resources.size() == 0:
		printerr("Not found player resource by country:", country)
		return
	var venue := Player.PlayerVenue.HOME if own_goal.goal_location == Goal.GoalLocation.HOME else Player.PlayerVenue.AWAY
	for i in player_resources.size():
		var node := spawns.get_child(i) as Node2D
		var player_position := node.global_position
		var player_resource := player_resources[i] as PlayerResource
		var player := _spawn_player(player_position, venue, player_resource)
		if player:
			add_child(player)


func _spawn_player(player_position: Vector2, venue: Player.PlayerVenue, player_resource: PlayerResource) -> Player:
	var player := GlobalConstants.PLAYER_PREFAB.instantiate() as Player
	if not player:
		printerr("Cannot instantiate player")
		return null

	prints("venue:", venue, "pos:", player_position)
	player.initialize(player_position, venue, player_resource)
	return player
